package org.bambrikii.payment.gateways.roboxchange;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import javax.xml.namespace.QName;

import org.bambrikii.payment.conversion.CurrencyConversionException;
import org.bambrikii.payment.conversion.CurrencyConverter;

import com.roboxchange.merchant.webservice.RatesList;
import com.roboxchange.merchant.webservice.Service;
import com.roboxchange.merchant.webservice.ServiceSoap;

public class RoboxchangeService implements CurrencyConverter {
	public static final String URL = "https://merchant.roboxchange.com/WebService/Service.asmx?WSDL";
	private String merchantLogin;
	private ServiceSoap serviceSoap;

	public RoboxchangeService(String merchantLogin) throws RoboxchangeServiceException {
		try {
			this.merchantLogin = merchantLogin;
			QName portName1 = new QName("http://merchant.roboxchange.com/WebService/", "Service");
			serviceSoap = new Service(new URL(URL), portName1).getPort(ServiceSoap.class);
		} catch (MalformedURLException ex) {
			throw new RoboxchangeServiceException("RoboxchangeService initialization failed", ex);
		}
	}

	public BigDecimal getRate(String incCurrLabel, BigDecimal outSum, String language) throws RemoteException,
			RoboxchangeServiceException {
		if (incCurrLabel == null || "".equals(incCurrLabel)) {
			throw new RoboxchangeServiceException("incCurrLabel parameter required");
		}
		RatesList rl = serviceSoap.getRates(merchantLogin, incCurrLabel, outSum, language);
		if (rl != null && rl.getGroups() != null && rl.getGroups().getGroup().size() == 1
				&& rl.getGroups().getGroup().get(0).getItems() != null
				&& rl.getGroups().getGroup().get(0).getItems().getCurrency().size() == 1) {
			return rl.getGroups().getGroup().get(0).getItems().getCurrency().get(0).getRate().getIncSum();
		} else {
			throw new RoboxchangeServiceException("Incorrect records count to be returned");
		}
	}

	@Override
	public Double convertTo(Double srcAmount, String dstCurrency) throws CurrencyConversionException {
		try {
			return new Double(getRate(dstCurrency, new BigDecimal(srcAmount), null).toString());
		} catch (Exception ex) {
			throw new CurrencyConversionException("Currency conversion failed");
		}
	}
}
